<?php
if(!defined('SITE_PATH')) exit;
define('ROOM_STATUS', [
    '1' => '准备阶段',
    '2' => '战斗阶段',
]);
define('ROUND_STATUS', [
    '1' => '抽卡阶段',
    '2' => '操作阶段',
]);
// GAMESTATUS
define('GAME_START', 1);
define('ROUND_START', 2);
// ROUNDSTATUS
define("ROUND_RCD", 1); // 摸牌阶段
define("ROUND_OPT", 2); // 操作阶段

// define('SITE_PATH', dirname(__FILE__).'/');

require_once __DIR__ . '/Connection.php';
require_once __DIR__ . '/Player.class.php';
require_once __DIR__ . '/Room.class.php';

$GLOBALS['myconfig'] = include "./config.php";
$mysql = $GLOBALS['myconfig']['mysql'];

$GLOBALS['db'] = new \Workerman\MySQL\Connection($mysql['host'], $mysql['port'], $mysql['user'], $mysql['password'], $mysql['db_name']);

$GLOBALS['user'] = null;

$GLOBALS['room'] = null;
define('help', 'help');

define('cardadd', 'cardadd');
define('cardck', 'cardck');
define('cardrmall', 'cardrmall');
define('cardrm', 'cardrm');
define('user', 'user');
define('userck', 'userck');
define('entergame', 'entergame');
define('round', 'round');
define('enemy', 'enemy');
define('reg', 'reg');
define('upinfo', 'upinfo');
define('upxp', 'upxp');

define('dmadd', 'dmadd');
define('dmcardck', 'dmcardck');
define('dmcardset', 'dmcardset');
define('dmuserhp', 'dmuserhp');
define('dmuserxp', 'dmuserxp');
define('dmusermp', 'dmusermp');
define('dmuserattr', 'dmuserattr');
define('dmuserck', 'dmuserck');
define('dmaddenemy', 'dmaddenemy');
define('dmaddenemycard', 'dmaddenemycard');

define('gamestart', 'gamestart');
define('gameck', 'gameck');
define('gameover', 'gameover');
define('roundstart', 'roundstart');
define('gameplayerck', 'gameplayerck');
define('roundck', 'roundck');


define('atk', 'atk');   // 攻击
define('opt', 'opt');  // 操作
define('opt2', 'opt2');  // 操作
define('rcd', 'rcd');  // 抽卡 
define('red', 'red'); // 回合结束
define('delcard', 'delcard'); // 移除卡牌
define('appcd', 'appcd'); // 游戏中向某人墓地添加卡牌


define('dmatk', 'dmatk');  // 操作
define('dmrcd', 'dmrcd');  // 抽卡 
define('dmred', 'dmred'); // 回合结束



function userhelp(){
     $msg .= "设定角色以及卡片
            reg 注册 例:reg 齐天大圣 特性
            userck 查看自己角色信息
            cardadd 添加卡到卡组 例：cardadd 卡1 卡2
            cardck 查看自己卡组
            cardrm 删除卡片 卡id 例:cardrm 1,2,3
            cardrmall 删除所有卡片 例:cardrmall
            upinfo 修改自己角色名称 upinfo 小白龙
            upxp 修改自己角色经验 upxp +10\n";
            
    $msg .= "dm相关
            dmadd 添加自己为dm
            dmuserhp 修改角色hp 例:dmuserhp 齐天大圣 10
            dmuserxp 修改角色xp 例:dmuserxp 齐天大圣 +10
            dmusermp 修改角色mp 例:dmusermp 齐天大圣 10
            dmuserattr 修改角色特性 例:dmuserattr 齐天大圣 特性2
            dmuserck 查看角色 例:dmuserck 齐天大圣 
            dmcardset 修改卡片描述 例:dmcardset 14 这是一张卡片
            dmcardck 查看卡组信息 例:dmcardck 卡id||不填查看所有\n";
    return $msg;
}
function gamehelp(){
     $msg .= "dm游戏相关
            gamestart 开启本群游戏 例:gamestart 游戏名称
            dmaddenemy dm添加敌人 
            例:dmaddenemy id name hp mp attr
            dmaddenemycard dm为敌人添加卡牌 
            例:dmaddenemycard 敌人id 吐纳,吐纳
            gameck 查看群游戏信息
            gameplayerck 查看正在游戏角色信息
            roundstart 游戏开始
            gameover 游戏结束\n";
            
    $msg .= "player游戏相关
            entergame 加入游戏
            rcd 抽卡 例:rec 3||不填默认3
            atk 攻击 例:atk 对齐天大圣使用三张击打造成3点伤害
            opt 实际效果修改 例:opt 齐天大圣,hp-3,mp-1 说书人,mp+1
            opt2 实际效果修改 例:opt 齐天大圣 hp -3
            delcard 将回合中玩家手牌移出本局游戏 例:delcard 13,14
            red 回合结束
            appcd 游戏中墓地添加卡牌 例:appcd 齐天大圣 吐纳,吐纳 \n";
    $msg .= "enemy游戏相关
            dmrcd dm控制敌人抽卡 例:rec 敌人id 3||不填默认3
            dmatk dm控制敌人攻击 
            例:atk 敌人id 对齐天大圣使用三张击打造成3点伤害
            dmred dm控制敌人回合结束 例:dmred 敌人id";
    $msg .= "相关说明
            || 这个符号代表或
            所有输入中的逗号均为英文状态下逗号 
            加入游戏前进行注册
            help 说明";
    return $msg;
}
/*
    ps:为实装卡片效果之前只是说明。
    ps:移除卡牌操作必须在玩家回合内切只能移除当前回合玩家手牌
*/

function getdb(){
    return $GLOBALS['db'];
}

function getuser(){
    return $GLOBALS['user'];
}

function initUser($fromQQ){
    $sql = "select * from user where fromqq = $fromQQ limit 0,1";
    $re = getdb()->query($sql);

    if(!empty($re)){
        $GLOBALS['user'] = $re[0];    
    }
}
function getRoom(){
    return $GLOBALS['room'];
}

function initRoom($fromGroup){
    $GLOBALS['room'] = MyRedis::get("room:".$fromGroup);
    if(empty($GLOBALS['room'])){
        return null;
    }
    return $GLOBALS['room'];
}

function setRoom($room,$fromGroup){
    $s = serialize($room);
    return MyRedis::set("room:".$fromGroup,$s);
}
/**
 * 收到私聊消息
 * @event 1
 * @param CoolQ $CQ API Class
 * @param int $subType 消息子类型，11/来自好友 1/来自在线状态 2/来自群 3/来自讨论组
 * @param int $time 消息发送事件(10位时间戳)
 * @param int $msgID 消息ID
 * @param int $fromQQ 来源QQ
 * @param string $msg 消息内容
 * @param array $info 该事件的所有信息
 */
function _event_PrivateMsg(CoolQ $CQ, $subType, $time, $msgID, $fromQQ, $msg, array $info)
{
    
    // $reply = "subType = $subType\n";
    // $reply .= "time = $time\n";
    // $reply .= "msgID = $msgID\n";
    // $reply .= "fromQQ = $fromQQ\n";
    // $reply .= "msg = $msg";
    // $CQ->sendPrivateMsg($fromQQ, $reply);
    $fromQQ = "".$fromQQ;

    if($msg == "收到福袋，请使用新版手机QQ查看"){
        $CQ->sendPrivateMsg($fromQQ, "去死吧");    
    }

    if($msg == "哄我"){
        require_once __DIR__ . '/saohua.class.php';
        $sqohua = new Saohua();
        $re = $sqohua->getsaohua();

        $CQ->sendPrivateMsg($fromQQ, $re);
        die();
    }
        
    // _eventmsgreg
    // if($msg == ".gameinit"){
    //     $reply = "gameinit";
    //     $CQ->sendPrivateMsg($fromQQ, $reply);
    // }
    $fromGroup = "34550";
    initUser($fromQQ);
    $msg = msgformat($msg);
    if($msg[0] == help){

        $userhelp = userhelp();
        $gamehelp = gamehelp();
        $CQ->sendPrivateMsg($fromQQ, $userhelp);
        $CQ->sendPrivateMsg($fromQQ, $gamehelp);
        die();
    }

    if($msg[0] == admintest){
        $fromQQ = "2726548204";
        $fromGroup = "345104750";
        $room = initRoom($fromGroup);
        var_dump($room);

        $CQ->sendPrivateMsg($fromQQ, $name . $reply);
        return; 
    }

    $fromGroup = "345104750";
    //$fromQQ = "2726548204";
    // $CQ->sendPrivateMsg($fromQQ, $msg[1]);
    // return;

    $reply = _eventmsgreg($msg,$fromQQ,$fromGroup,$CQ);
    if(is_array($reply)){
        $reply = json_encode($reply,JSON_UNESCAPED_UNICODE);
    }
    if(!empty($reply)){
        $name = getusername($fromQQ,$fromGroup);
        $CQ->sendPrivateMsg("837424187", $name . $reply);
    }
}

/**
 * 收到群消息
 * @event 2
 * @param CoolQ $CQ API Class
 * @param int $subType 消息子类型，1/普通消息 2/匿名消息 3/系统消息
 * @param int $time 消息发送时间(10位时间戳)
 * @param int $msgID 消息ID
 * @param int $fromGroup 来源群
 * @param int $fromQQ 来源QQ
 * @param string $msg 消息内容
 * @param array $info 该事件的所有信息
 */
function _event_GroupMsg(CoolQ $CQ, $subType, $time, $msgID, $fromGroup, $fromQQ, $msg, array $info)
{
    /*
    $reply = "subType = $subType\n";
    $reply .= "time = $time\n";
    $reply .= "msgID = $msgID\n";
    $reply .= "fromGroup = $fromGroup\n";
    $reply .= "fromQQ = $fromQQ\n";
    $reply .= "msg = $msg";
    $CQ->sendGroupMsg($fromGroup, $reply);
    */

    /*
    if($msg == '你好') {
        $CQ->sendGroupMsg($fromGroup, "你好\r\n我是小娜");
        $CQ->sendGroupMsg($fromGroup,'你是我的闺蜜Sir吗');
        $CQ->sendGroupMsg($fromGroup, $CQ->cqAt($fromQQ));
    }
    //撤回消息
    //$CQ->setMsgDelete($msgID);
    if($subType == 2) {
        //收到匿名消息
        $anonymousInfo = $info['anonymousInfo'];
        //$anonymousInfo['name']; //匿名用户代号
        //禁言匿名成员1分钟
        $CQ->setGroupAnonymousBan($fromGroup, $info['fromAnonymous'], 60);
    }
    */

     if($subType == 2) {
        //收到匿名消息
        // $anonymousInfo = $info['anonymousInfo'];
        //$anonymousInfo['name']; //匿名用户代号
        //禁言匿名成员1分钟
        // $CQ->setGroupAnonymousBan($fromGroup, $info['fromAnonymous'], 60);
        return;
    }

    // if($fromGroup == "99437797"){
    //     if(strpos($msg,"gg") !== false){
    //         // $reply = "gameinit";
    //         $chengyu = substr($msg, 2);
    //         $reply = file_get_contents("http://i.itpk.cn/api.php?question=@cy$chengyu");
    //         $CQ->sendGroupMsg($fromGroup, "智障接龙1.0 " . $reply);
    //     }
    // }
    $groupids = ["345104750","99437797"];
    if(in_array($fromGroup, $groupids)){
        $fromQQ = "".$fromQQ;
        initUser($fromQQ);
        $msg = msgformat($msg);
        if($msg[0] == help){
            $userhelp = userhelp();
            $gamehelp = gamehelp();
            $CQ->sendGroupMsg($fromGroup, $userhelp);
            $CQ->sendGroupMsg($fromGroup, $gamehelp);
            die();
        }
        $reply = _eventmsgreg($msg,$fromQQ,$fromGroup,$CQ);
        if(is_array($reply)){
            $reply = json_encode($reply,JSON_UNESCAPED_UNICODE);
        }
        if(!empty($reply)){
            $name = getusername($fromQQ,$fromGroup);
            $CQ->sendGroupMsg($fromGroup, $name . $reply);
        } 
    }
    // if($msg == "收到福袋，请使用新版手机QQ查看"){
    //     $CQ->sendPrivateMsg($fromQQ, "去死吧");    
    // }

    // if($msg == "收到福袋，请使用新版手机QQ查看"){
    //     $CQ->setGroupBan($fromGroup, $fromQQ, 60);
    // }

}

/**
 * 收到讨论组消息
 * @event 4
 * @param CoolQ $CQ API Class
 * @param int $subType 消息子类型，该事件下固定为 1
 * @param int $time 消息发送时间(10位时间戳)
 * @param int $msgID 消息ID
 * @param int $fromDiscuss 来源讨论组号
 * @param int $fromQQ 来源QQ
 * @param string $msg 消息内容
 * @param array $info 该事件的全部信息
 */
function _event_DiscussMsg(CoolQ $CQ, $subType, $time, $msgID, $fromDiscuss, $fromQQ, $msg, array $info)
{
    /*
    $reply = "subType = $subType\n";
    $reply .= "time = $time\n";
    $reply .= "msgID = $msgID\n";
    $reply .= "fromDiscuss = $fromDiscuss\n";
    $reply .= "fromQQ = $fromQQ\n";
    $reply .= "msg = $msg";
    $CQ->sendDiscussMsg($fromDiscuss, $reply);
    */
}


/**
 * 群文件上传事件
 * @event 11
 * @param CoolQ $CQ API Class
 * @param int $subType 事件子类型，该事件下固定为 1
 * @param int $time 事件产生时间(10位时间戳)
 * @param int $fromGroup 来源群号
 * @param int $fromQQ 上传者QQ号
 * @param string $file 上传文件信息
 * @param array $info 该事件所有信息，包含解析后的文件信息 fileInfo
 */
function _event_GroupFileUpload(CoolQ $CQ, $subType, $time, $fromGroup, $fromQQ, $file, array $info)
{
    /*
    $fileInfo = $info['fileInfo'];
    $msg = $CQ->cqAt($fromQQ)."上传了文件\n";
    $msg .= '文件名：'.$fileInfo['name']."\n";
    $msg .= '文件大小：'.$fileInfo['size'].' B';
    $CQ->sendGroupMsg($fromGroup, $msg);
    */
    // 删除文件
    // $CQ->setGroupFileDelete($fromGroup, $fileInfo['busid'], $fileInfo['id']);
}


/**
 * 管理员变动事件
 * @event 101
 * @param CoolQ $CQ API Class
 * @param int $subType 事件子类型，1/被取消管理员 2/被设置管理员
 * @param int $time 事件产生时间(10位时间戳)
 * @param int $fromGroup 来源群号
 * @param int $beingOperateQQ 被操作QQ
 * @param array $info 该事件的所有信息
 */
function _event_GroupAdminChange(CoolQ $CQ, $subType, $time, $fromGroup, $beingOperateQQ, array $info)
{
    /*
    $msg = $CQ->cqAt($beingOperateQQ);
    $msg .= '被'.($subType == 1 ? '取消' : '设置为').'管理员';
    $CQ->sendGroupMsg($fromGroup, $msg);
    */
}


/**
 * 群成员减少事件
 * @event 102
 * @param CoolQ $CQ API Class
 * @param int $subType 事件子类型，1/群员退群 2/群员被踢
 * @param int $time 事件产生时间(10位时间戳)
 * @param int $fromGroup 来源群号
 * @param int $fromQQ 操作者QQ(仅subType==2时存在)
 * @param int $beingOperateQQ 退群者||被踢者
 * @param array $info 该事件的所有信息
 */
function _event_GroupMemberDecrease(CoolQ $CQ, $subType, $time, $fromGroup, $fromQQ, $beingOperateQQ, array $info)
{
    /*
    $msg = '';
    $qqInfo = $CQ->getStrangerInfo($beingOperateQQ);
    if($qqInfo['status'] == 0) {
        $qqInfo = $qqInfo['result'];
        $msg = $CQ->cqImage($qqInfo['headimg']);
    }
    $msg .= '有个群员';
    $msg .= ($subType == 1) ? '退群了' : '被踢了';
    $CQ->sendGroupMsg($fromGroup, $msg);
    */
}


/**
 * 群成员增加事件
 * @event 103
 * @param CoolQ $CQ API Class
 * @param int $subType 事件子类型，1/管理员已同意 2/管理员邀请
 * @param int $time 事件产生时间(10位时间戳)
 * @param int $fromGroup 来源群
 * @param int $fromQQ 操作者QQ(即管理员QQ)
 * @param int $beingOperateQQ 被操作QQ(即加群的QQ)
 * @param array $info 该事件的所有信息
 */
function _event_GroupMemberIncrease(CoolQ $CQ, $subType, $time, $fromGroup, $fromQQ, $beingOperateQQ, array $info)
{
    /*
    $msg = '欢迎'.$CQ->cqAt($beingOperateQQ);
    $groupTopNote = $CQ->getGroupTopNote($fromGroup);
    if($groupTopNote['status'] == 0 && !empty($groupTopNote['result'])) {
        $groupTopNote = $groupTopNote['result'];
        $msg .= "\n";
        $msg .= $groupTopNote['msg']['text'];
    }
    $CQ->sendGroupMsg($fromGroup, $msg);
    */
}


/**
 * 已添加好友事件
 * @event 201
 * @param CoolQ $CQ API Class
 * @param int $subType 事件子类型，在此事件中固定为 1
 * @param int $time 事件产生时间(10位时间戳)
 * @param int $fromQQ 添加好友的QQ
 * @param array $info 该事件的所有信息
 */
function _event_FriendIsAdd(CoolQ $CQ, $subType, $time, $fromQQ, array $info)
{
    /*
    $reply = '我们成为好友了，快来聊天吧';
    $CQ->sendPrivateMsg($fromQQ, $reply);
    */
}


/**
 * 事件_添加好友请求
 * @event 301
 * @param CoolQ $CQ API Class
 * @param int $subType 事件子类型，该事件下固定为 1
 * @param int $time 事件产生时间(10位时间戳)
 * @param int $fromQQ 发送添加好友请求的QQ
 * @param string $msg 附言
 * @param string $responseFlag 处理标识，调用api需要使用
 * @param array $info 该事件的所有信息
 */
function _event_RequestAddFriend(CoolQ $CQ, $subType, $time, $fromQQ, $msg, $responseFlag, array $info)
{
    //通过请求
    //$CQ->setFriendAddRequest($responseFlag, 1, '这是备注');
    //拒绝请求
    //$CQ->setFriendAddRequest($responseFlag, 2);
}


/**
 * 事件_添加群请求
 * @event 302
 * @param CoolQ $CQ API Class
 * @param int $subType 事件子类型，1/他人申请入群 2/自己(即机器人)受邀入群
 * @param int $time 事件产生时间(10位时间戳)
 * @param int $fromGroup 来源群号
 * @param int $fromQQ 发送请求的QQ
 * @param string $msg 加群理由
 * @param string $responseFlag 处理标识
 * @param array $info 该事件的全部信息
 */
function _event_RequestAddGroup(CoolQ $CQ, $subType, $time, $fromGroup, $fromQQ, $msg, $responseFlag, array $info)
{
    //通过请求
    //$CQ->setGroupAddRequest($responseFlag, $subType, 1);
    //拒绝请求
    //$CQ->setGroupAddRequest($responseFlag, $subType, 2, '拒绝理由');
}

/*解析msg*/
function _eventmsgcard($msg,$fromQQ,$fromGroup,$CQ){
    if(strpos($msg,"card") !== false && strpos($msg,"card")==0){
        $info = explode(" ",$msg);//$msg
        if($info[0] == "cardset"){

            $addcards = explode(",", $info[1]);

            $cards = MyRedis::get("cardset".$fromQQ);
            if(isset($info[2]) && $info[2] == "add"){ // 添加
                $cards = !empty($cards) ? $cards : [];
               $cards = array_merge($cards,$addcards);

            }else{ // init
                $cards = $addcards;
            }
            MyRedis::set("cardset".$fromQQ,$cards);

            $cards = MyRedis::get("cardset".$fromQQ);
            return $cards;
        }

        else if($info[0] == "cardadd"){
            $cards = MyRedis::get("cardset".$fromQQ);
            foreach ($info as $key => $value) {
                if($key != 0 && !empty($value)){
                    $id = getId();
                    $cards[$id] = $value;
                }
            }
            MyRedis::set("cardset".$fromQQ,$cards);
            $cards = MyRedis::get("cardset".$fromQQ);
            return $cards;
        }

        else if($info[0] == "cardrmall"){
            
            $cards = MyRedis::get("cardset".$fromQQ);
            for ($i=1; $i <= count($info); $i++) { 
                if(!empty($info[$i]) && isset($cards[$info[$i]])){
                    unset($cards[$info[$i]]);                    
                }
            }
            
            MyRedis::set("cardset".$fromQQ,$cards);
            $cards = MyRedis::get("cardset".$fromQQ);
            return $cards;
        }

        else if($info[0] == "cardremoveall"){
            MyRedis::set("cardset".$fromQQ,[]);
            MyRedis::set("cardset1".$fromQQ,[]);
            $cards = MyRedis::get("cardset".$fromQQ);
            return $cards;
        }


        else if($info[0] == "cardget"){
            if($info[1] == "0"){
                $cards = MyRedis::get("cardset".$fromQQ);
                $cards1 = MyRedis::get("cardset1".$fromQQ);
                return array_merge($cards,$cards1);
            }

            if ((int)$info[1] > 0) {
                $cards = MyRedis::get("cardset".$fromQQ); // 待抽
                $cards1 = MyRedis::get("cardset1".$fromQQ); // 已抽

                $random_keys = array_rand($cards,$info[1]);

                if($random_keys == null) {
                    $test = [];
                    if(!empty($cards)){
                        $info[1] = $info[1] - count($cards);
                        $test = $cards;
                    }
            
                    $cards = $cards1;
                    $cards1 = $test;

                    $random_keys = array_rand($cards,$info[1]);

                    if($random_keys == null){
                        return "小老弟 不要搞我啊 你所有牌加起来也没这么多啦";
                    }

                    MyRedis::set("cardset".$fromQQ,$cards);
                    MyRedis::set("cardset1".$fromQQ,$cards1);
                }

                
                if(!is_array($random_keys)){
                    $re = [$random_keys=>$cards[$random_keys]];
                    $cards1[$random_keys] = $cards[$random_keys];
                    unset ($cards[$random_keys]);


                }else{
                    $re = [];
                    foreach ($random_keys as $randomkey) {
                        $re[$randomkey] = $cards[$randomkey];

                        $cards1[$randomkey] = $cards[$randomkey];
                        unset ($cards[$randomkey]);
                    }
                }

                if(!empty($test)){
                    $re = $re + $test;
                }

                MyRedis::set("cardset".$fromQQ,$cards);
                MyRedis::set("cardset1".$fromQQ,$cards1);
                $CQ->sendPrivateMsg($fromQQ, json_encode($re,JSON_UNESCAPED_UNICODE));
                return "已发牌 至 $fromQQ";
            }
        }

        else if($info[0] == "resetids"){
            MyRedis::set("cardsetids",null);
        }

        else if($msg[0] == "cardcheck"){
            $cards = MyRedis::get("cardset".$fromQQ);
            $cards1 = MyRedis::get("cardset1".$fromQQ);
            
            if($info[1] == "one"){
                return $cards;
            }else if ($info[1] == "two") {
                return $cards1;
            }else{
                return ["待抽"=>$cards,"已抽"=>$cards1];
            }
        }

        else if($info[0] == "cardaddhost"){ // 添加管理员
            if($fromGroup == null) return "error 群组id错误";
            $cardaddhost = MyRedis::get("cardaddhost".$fromGroup);

            foreach ($info as $key => $value) {
                if($key != 0 && !empty($value) && !in_array($value, $cardaddhost)){
                    $cardaddhost[] = $value;
                }
            }

            MyRedis::set("cardaddhost".$fromGroup,$cardaddhost);
            $cardaddhost = MyRedis::get("cardaddhost".$fromGroup);
            return $cardaddhost;
        }

        else if ($info[0] == "cardremovehost") { // 删除本群管理员
            if($fromGroup == null) return "error 群组id错误";
            $cardaddhost = MyRedis::get("cardaddhost".$fromGroup);

            foreach ($info as $key => $value) {
                if($key != 0 && !empty($value)){
                    $qqkey = array_search($value, $cardaddhost);
                    if ($key !== false)
                        array_splice($cardaddhost, $qqkey, 1);

                }
            }
            MyRedis::set("cardaddhost".$fromGroup,$cardaddhost);
            return $cardaddhost;
        }

        elseif ($info[0] == "cardshuffle") { // 管理员洗牌
            if($fromGroup == null) return "error 群组id错误";

            $cardaddhost = MyRedis::get("cardaddhost".$fromGroup);  
            if(!empty($cardaddhost) && in_array($fromQQ, $cardaddhost)){
                $re = cardshuffle($fromGroup);

                return $re == true ? "洗牌ok" : $re;

            }else{
                return "权限不足";
            }
        }

        else if ($info[0] == "cardgroup") { // qun => [qq,qq] 绑定群 id
            if($fromGroup == null) return "error 群组id错误";
            $group = MyRedis::get("group".$fromGroup);
            $group = !empty($group)?$group:[];
            if(empty($group) || !in_array($fromQQ, $group)){
                $group[] = $fromQQ;
                MyRedis::set("group".$fromGroup,$group);
            }   
            $gameuser = MyRedis::get("gameuser".$fromGroup); // 游戏user变更
            if(empty($gameuser) || !isset($gameuser[$fromQQ])){
                $user = $CQ->getGroupMemberInfo($fromGroup,$fromQQ);
                if($user['status'] == 0){
                    $gameuser[$fromQQ] = [
                        "name" => $user['result']['name'],
                        "card" => $user['result']['card'],
                        "qq" => $fromQQ, 
                    ];
                }
                MyRedis::set("gameuser".$fromGroup,$gameuser);
            }

            return "绑定本群成功";
        }

        else if ($info[0] == "cardremovegroup") { // 解绑群组id
            if($fromGroup == null) return "error 群组id错误";
            $group = MyRedis::get("group".$fromGroup);

            if(empty($group) || !in_array($fromQQ, $group)){
                return "error 未绑定此群组";
            }else{
                $key = array_search($fromQQ, $group);
                if ($key !== false)
                    array_splice($group, $key, 1);
            }

            MyRedis::set("group".$fromGroup,$group);

            $gameuser = MyRedis::get("gameuser".$fromGroup); // 游戏user变更
            unset($gameuser[$fromQQ]);
            MyRedis::set("gameuser".$fromGroup,$gameuser);
            return $group;
        }
        else if($info[0] == "cardhelp"){
            return helpme();
        }
        else if($info[0] == "cardadmin"){ // 后台执行窗口
            $gameuser = MyRedis::get("gameuser".$fromGroup);
            $CQ->sendPrivateMsg($fromQQ, json_encode($gameuser,JSON_UNESCAPED_UNICODE));
            // $CQ->sendGroupMsg($fromGroup, json_encod($getusername,JSON_UNESCAPED_UNICODE)); 
        }
        // return "ok";
    }
    else{
        return _eventmsground($msg,$fromQQ,$fromGroup,$CQ);
    }
}

function _eventmsground($msg,$fromQQ,$fromGroup,$CQ){
    if(strpos($msg,"round") !== false && strpos($msg,"round")==0){
        $info = explode(" ",$msg);//$msg

        if($info[0] == "roundstart"){ // 回合开始
            if($fromGroup == null) return "error 群组id错误";
            $cardaddhost = MyRedis::get("cardaddhost".$fromGroup);  
            if(!empty($cardaddhost) && in_array($fromQQ, $cardaddhost)){
                $re = cardshuffle($fromGroup);
                if($re !== true) return $re;

                MyRedis::set("roundstate".$fromGroup,"start");  // 回合状态  开始
                /*随机roll点*/
                MyRedis::rolldian("roundroll".$fromGroup);
                /*roll点信息存储*/
                MyRedis::set("rolldata".$fromGroup,[]);
                return "先攻模式开启 玩家roll点";

            }else{
                return "权限不足 管理员才能开启";
            }
        }

        else if ($info[0] == "roundroll") {
            if($fromGroup == null) return "error 群组id错误";
            $roundstate = MyRedis::get("roundstate".$fromGroup);  // 回合状态  开始
            if($roundstate == "start"){
                $rolldata = MyRedis::get("rolldata".$fromGroup);  // roll点的信息存储
                if(!empty($rolldata) && in_array($fromQQ,$rolldata)){
                    return array_search($fromQQ, $rolldata) . " 已经roll过";
                }else{
                    $dian = MyRedis::lpop("roundroll".$fromGroup);
                }
                $rolldata[$dian] = $fromQQ;
                MyRedis::set("rolldata".$fromGroup,$rolldata);
                return $dian ;
            }else{
                return "error 请开启先攻模式";
            }
        }

        else if ($info[0] == "roundrollend") { // roll点结束
            $roundstate = MyRedis::get("roundstate".$fromGroup);
            if($roundstate !== "start"){
                // return "error 非roll点环节";
            }
            $rolldata = MyRedis::get("rolldata".$fromGroup);
            sort($rolldata);
            $msg = "roll点结束 攻击顺序如下 \n";

            $gameuser = MyRedis::get("gameuser".$fromGroup);
            foreach ($rolldata as $value) {
                if(empty($gameuser[$value])){
                    $msg .= $value .  " qq未绑定 \n";    
                }else{
                    $msg .= $gameuser[$value]['card'] . " \n";
                }
            }

            MyRedis::set("rolldata".$fromGroup,$rolldata);
            MyRedis::set("roundstate".$fromGroup,"rollend");  // roll点结束
            $CQ->sendGroupMsg($fromGroup, $msg);
            nextuserroundstart($fromGroup,$CQ);
        }

        else if ($info[0] == "roundover") { // 个人回合结束
            return userroundend($fromQQ,$fromGroup,$CQ);
        }else if ($info[0] == "roundoverall") { // 游戏结束
            $re = checkauth($fromGroup,$fromQQ);
            if($re!==true) return $re;
            MyRedis::set("roundstate".$fromGroup,"roundend");  // 游戏结束结束
            return "roundend ok";
        }
    }
}
    
/*注册*/
function _eventmsgreg($msg,$fromQQ,$fromGroup,$CQ){
    $db = getdb();
    if($msg[0] == reg){
        
        $name = $msg[1];
        $characteristic = $msg[2];
        $time = time();
        if(defined($name)) {
            return "不可以使用命令作为游戏昵称";
        }
        try {
            $sql = "INSERT INTO `user` ( `fromqq`,`nickname`,`characteristic`,`ctime`)
                                VALUES ( '$fromQQ', '$name', '$characteristic','$time')";
            // return $sql;

            $db->query($sql);
        } catch (Exception $e) {
            return "已经存在";    
        }
        initUser($fromQQ);
        return "注册成功";
    }
    elseif ($msg[0] == upinfo) {
        $name = $msg[1];
        if(defined($name)) {
            return "不可以使用命令作为游戏昵称";
        }
        $user = getuser();
        if(empty($user)){
            return "请先注册";
        }
        $attr = $msg[2];
        if(empty($attr)){
            $sql = "UPDATE user set nickname = '$name' WHERE fromqq = $fromQQ";
        }else{
            $sql = "UPDATE user set nickname = '$name',characteristic='$attr' WHERE fromqq = $fromQQ";
        }
        
        $db->query($sql);
        initUser($fromQQ);
        $user = getuser();
        return userformat($user); 
    }
    elseif ($msg[0] == upxp) {
        $user = getuser();
        if(empty($user)){
            return "请先注册";
        }
        $xp = $msg[1];
        $xp1 = $user['xp'] + $xp;
        $sql = "UPDATE user set xp = $xp1 WHERE fromqq = $fromQQ";
        
        $db->query($sql);
        initUser($fromQQ);
        $user = getuser();
        return userformat($user); 
    }
    elseif ($msg[0] == dmadd) {
        $sql = "UPDATE `user` SET `isdm` = 1 WHERE `fromqq`= $fromQQ";
        $re = $db->query($sql);
        if($re){
            return "申请dm成功";    
        }else{
            return "请先注册";
        }
        
    }
    elseif ($msg[0] == userck) {
        $user = getuser();
        return userformat($user);
    }
    elseif ($msg[0] == entergame) {  // 加入游戏
        $user = getuser();
        if(empty($user)){
            return "请先注册";
        }
        $room = initRoom($fromGroup);
        $ch = checkRoom($room);
        if($ch !== true){
            return $ch;
        }
        // if(empty($room)){
        //     return "游戏未开始";
        // }
        // if($room->status != 1) return "游戏已经开始";

        $player = new Player($user['nickname'],$user['lifevalue'],$user['bluequantity'],$user['characteristic'],$user['fromqq']);
        $cards = getmycard($fromQQ,false);
        $player->initcards($cards);
        $en = $room->enterRoom($player);
        if(!$en){
            return "加入失败";
        }
        $re = setRoom($room,$fromGroup);
        if($re){
            return formatRoom(initRoom($fromGroup));
        }else{
            return "加入失败";
        }
    }
    else{
        $db = getdb();
        $sql = "select * from user where fromqq = $fromQQ limit 0,1";
        $re = $db->query($sql);
        if($re){
            return _eventmsgcard2($msg,$fromQQ,$fromGroup,$CQ);
        }else{
            return "请先注册";
        }
    }
}
function _eventmsgcard2($msg,$fromQQ,$fromGroup,$CQ){


    if(strpos($msg[0],"card") !== false && strpos($msg[0],"card") == 0){
        $info = $msg;
        if($msg[0] == cardadd){
            $db = getdb();
            $sql = "INSERT INTO `card` ( `fromqq`,`c_name`)
                                VALUES ";
            foreach ($msg as $key => $value) {
                if($key != 0 && !empty($value)){
                    $sql .= "('$fromQQ','$value'),";
                }
            }

            $sql = substr($sql, 0,-1);
            $db->query($sql);

            $re = getmycard($fromQQ);
            return $re;
        }

        else if($msg[0] == cardrm){
            $ids = $msg[1];
            if (!$ids) {
                die();
            }
            $sql = "delete from card where fromqq = $fromQQ and id in ($ids)";
            $db = getdb();
            $db->query($sql);
            $re = getmycard($fromQQ);
            return $re;
        }

        else if($msg[0] == cardrmall){
            $sql = "delete from card where 1=1 and fromqq = $fromQQ";
            $db = getdb();
            $db->query($sql);
            // $re = getmycard($fromQQ);
            return "删除成功";
        }
        else if($msg[0] == cardck){

            if(isset($msg[1])){
                $re = getCardbyId($msg[1]);
                return $re;
            }

            $re = getmycard($fromQQ);
            return $re;
        }
    }
    else{

        return _eventmsgdm($msg,$fromQQ,$fromGroup,$CQ);
    }
}

// dm相关
function _eventmsgdm($msg,$fromQQ,$fromGroup,$CQ){
    if(strpos($msg[0],"dm") !== false && strpos($msg[0],"dm") == 0){
        $db = getdb();
        $info = $msg;

        if(!checkdm($fromQQ)){
            return "权限不足";
        }
        if($msg[0] == dmcardck){
            $cardid = $msg[1];
            if($cardid){
                $re = getmycard($cardid);    
            } else{
                $re = getmycard("dm");
            }
            
            return $re;
        }
        else if($msg[0] == dmcardset){
            $cardid = $msg[1];
            $effect = $msg[2];

            $sql = "UPDATE card set effect = '$effect' where id = $cardid";
            $db->query($sql);

            return getCardbyId($cardid);
        }
        else if($msg[0] == dmuserhp){
            $from = $msg[1];
            $lifevalue = $msg[2];
            // return $from;
            $user = getUserInfoByQQOrName($from);
            if(empty($user)){
                return "查无此人";
            }
            
            $fromQQ = $user['fromqq'];
            $sql = "UPDATE user set lifevalue = $lifevalue where fromqq = $fromQQ";
            $db->query($sql);
            $user['lifevalue'] = $lifevalue;
            
            return userformat($user);
        }else if ($msg[0] == dmusermp) {
            $from = $msg[1];
            $bluequantity = $msg[2];
            // return $from;
            $user = getUserInfoByQQOrName($from);
            if(empty($user)){
                return "查无此人";
            }
            
            $fromQQ = $user['fromqq'];
            $sql = "UPDATE user set bluequantity = $bluequantity where fromqq = $fromQQ";
            $db->query($sql);
            $user['bluequantity'] = $bluequantity;
            
            return userformat($user);
        }elseif ($msg[0] == "dmuserattr") {
            $from = $msg[1];
            $characteristic = $msg[2];
            // return $from;
            $user = getUserInfoByQQOrName($from);
            if(empty($user)){
                return "查无此人";
            }
            
            $fromQQ = $user['fromqq'];
            $sql = "UPDATE user set characteristic = '$characteristic' where fromqq = $fromQQ";
            $db->query($sql);
            $user['characteristic'] = $characteristic;
            
            return userformat($user);
        }
        else if($msg[0] == dmuserxp){
            $from = $msg[1];
            $xp = $msg[2];
            // return $from;
            $user = getUserInfoByQQOrName($from);
            if(empty($user)){
                return "查无此人";
            }
            
            $fromQQ = $user['fromqq'];
            $xp = $user['xp'] + $xp;
            $sql = "UPDATE user set xp = $xp where fromqq = $fromQQ";
            $db->query($sql);
            $user['xp'] = $xp;

            return userformat($user);
        }
        elseif ($msg[0] == dmuserck) {
            $from = $msg[1];
            $user = getUserInfoByQQOrName($from);
            if(empty($user)){
                return "查无此人";
            }
            return userformat($user);
        }
        else if($msg[0] == "cardck"){
            $re = getmycard($fromQQ);
            return $re;
        }
        else if($info[0] == dmaddenemy){ // dm添加敌人
            $id = $msg[1];
            $name = $msg[2];
            $hp = $msg[3];
            $mp = $msg[4];
            $attr = $msg[5];

            $re = checkRe([$id,$name,$hp,$mp,$attr]);
            if(!$re){
                return "输入不合法";
            }

            $room = initRoom($fromGroup);

            $ch = checkRoom($room);
            if($ch !== true){
                return $ch;
            }

            $player = new Player($name,$hp,$mp,$attr,$id,0);
            $en = $room->enterRoom($player);
            if(!$en){
                return "加入失败";
            }
            $re = setRoom($room,$fromGroup);
            if($re){
                return formatRoom(initRoom($fromGroup)) . "\n 加入敌人成功，请设置卡牌";
            }else{
                return "加入失败";
            }

        }

        elseif ($msg[0] == dmaddenemycard) { // 添加卡牌
            $data = [
                'fromqq' => $msg[1],
                'c_name' => $msg[2],
            ];
            $re = checkRe($data);
            if(!$re){
                return "输入不合法";
            }

            $room = initRoom($fromGroup);
            $ch = checkRoom($room);
            if($ch !== true){
                return $ch;
            }
        
            $player = $room->getPlayerById($msg[1]);
            if($player){
                $player->addcards($msg[2]);
                // return $player->qipai;
                $room->updatePlayerInfo($player);
                setRoom($room,$fromGroup);
                return "卡组 : " . formatcard($player->qipai);
            }else{
                return "id错误";
            }

        }
    }
    
    return _eventmsggame($msg,$fromQQ,$fromGroup,$CQ);
    
}

// 游戏相关
function _eventmsggame($msg,$fromQQ,$fromGroup,$CQ){
    if(strpos($msg[0],"game") !== false && strpos($msg[0],"game") == 0){
        $db = getdb();
        $info = $msg;
        $room = initRoom($fromGroup);
        if($msg[0] == gamestart){
            if(!empty($room)){
                return "请先结束此群现有的游戏";
            }
        }else{
            if(empty($room)){
                return "群里无游戏";
            }
        }

        if($msg[0] == gamestart){
            if(!checkdm($fromQQ)){
                return "权限不足";
            }
            $gamename = $msg[1];

            $room = new Room();
            $room->roomid = $fromGroup;
            $room->dmid = $fromQQ;

            if(isset($msg[1])) $room->gamename = $msg[1];

            return setRoom($room,$fromGroup) ? "请开始加入游戏":"error1";
        }
        else if($msg[0] ==gameck){
            if(!checkdm($fromQQ)){
                return "权限不足";
            }
            return formatRoom($room);
        }
        elseif ($msg[0] == gameplayerck) {
            if(!checkdm($fromQQ)){
                return "权限不足";
            }
            return $room->playerformatInfo();
        }
        else if ($msg[0] == gameover) {
            if(!checkdm($fromQQ)){
                return "权限不足";
            }
            return MyRedis::delete("room:".$fromGroup) ? "ok" : "error";
        }
    }
    else{
        return _eventmsground2($msg,$fromQQ,$fromGroup,$CQ);
    }
}

// 回合相关
function _eventmsground2($msg,$fromQQ,$fromGroup,$CQ){
    
    $room = initRoom($fromGroup);

    if ($msg[0] == roundstart) {
        if(!checkdm($fromQQ)){
            return "权限不足";
        }
        // $room = initRoom($fromGroup);
        $ch = checkRoom($room);
        if($ch !== true) return $ch;

        $room->roundstart();
        if(setRoom($room,$fromGroup)){
            return 1;
        }else{
            return "失败";    
        }
        
    }elseif($msg[0] == rcd || $msg[0] == dmrcd){     // 摸牌
        // $room = initRoom($fromGroup);
        // return $msg[1];
        $ch = checkRoom($room,ROUND_START);
        if($ch !== true) return $ch;
        
        // return $fromQQ;


        if($msg[0] == rcd){
            $ch = $room->checkRoundRcd($fromQQ);
            $player = $room->getPlayerById($fromQQ);
            $getcardnum = empty($msg[1]) ? 3 : $msg[1];
        }else{
            if(!checkdm($fromQQ)){
                return "权限不足";
            }
            $player = $room->getPlayerById($msg[1]);
            $ch = $room->checkRoundRcd($msg[1]);
            $getcardnum = empty($msg[2]) ? 3 : $msg[2];
        }

        // return $ch . "," . $player->qqid;
        if(!$ch) return "不在游戏或非抽卡阶段";
        $cards = $player->cards;  // 卡池
        $qipai = $player->qipai; // 弃牌
        $handcard = [];           // 手牌

        if(count($cards) >= $getcardnum){
            $random_keys = array_rand($cards,$getcardnum);
        }else{
            if(count($cards) + count($qipai) > $getcardnum){
                $count = $getcardnum - count($cards);

                $handcard = $cards;
                $cards = $qipai;
                $qipai = [];

                $random_keys = array_rand($cards,$count); 
            }else{
                $handcard = $cards + $qipai;
                $cards = [];
                $qipai = [];
            }
        }
        if(!empty($random_keys)){
            if(!is_array($random_keys)){
                $handcard[$random_keys] = $cards[$random_keys];
                unset ($cards[$random_keys]);
            }else{
                $re = [];
                foreach ($random_keys as $randomkey) {
                    $handcard[$randomkey] = $cards[$randomkey];
                    unset ($cards[$randomkey]);
                }
            }
        }
        $player->cards = $cards;  // 卡池
        $player->qipai = $qipai; // 弃牌
        $player->handcard = $handcard;// 手牌
        $room->updatePlayerInfo($player);
        setRoom($room,$fromGroup);
        return "手牌: ".formatcard($handcard);
    }elseif ($msg[0] == atk || $msg[0] == dmatk) { // 攻击
        // $room = initRoom($fromGroup);
        $ch = checkRoom($room,ROUND_START);
        if($ch !== true) return $ch;
        if($msg[0] == atk){
            $ch = $room->checkRoundOpt($fromQQ);    
        }else{
            if(!checkdm($fromQQ)){
                return "权限不足";
            }
            $ch = $room->checkRoundOpt($msg[1]);
        }
        
        if(!$ch) return "不在游戏或非你的回合";
        return "操作达成";
    }elseif ($msg[0] == "cg") {     // 
        # code...
    }elseif($msg[0] == "cw"){

    }
    elseif($msg[0] == opt2){ // 操作
        $ch = checkRoom($room,ROUND_START);
        if($ch !== true) return $ch;
        $ch = $room->getPlayerByNameOrId($fromQQ);
        if(!$ch) return "不在游戏";

        $name = $msg[1];
        $optname = $msg[2];
        $num = (int)$msg[3];

        $re = checkRe([$name,$optname,$num]);
        if(!$re){
            return "输入不合法";
        }

        $player = $room->getPlayerByNameOrId($name);
        if($player === false) return "不在游戏";
        if($optname == "hp" || $optname == "mp"){
            $player->$optname = $player->$optname + $num;

        }else{
            return "输入不合法1";
        }
        $room->updatePlayerInfo($player);
        setRoom($room,$fromGroup);
        return $player->playerformatInfo();
    }elseif ($msg[0] == red || $msg[0] == dmred) {  // 回合结束
        $ch = checkRoom($room,ROUND_START);
        if($ch !== true) return $ch;
        if($msg[0] == red){
            $ch = $room->checkRoundOpt($fromQQ);
        }else{
            if(!checkdm($fromQQ)){
                return "权限不足";
            }
            $ch = $room->checkRoundOpt($msg[1]);
        }
        if(!$ch) return "不在游戏或非你的回合";
        $room->roundend();
        setRoom($room,$fromGroup);
        return "回合结束 \n" . $room->playerformatInfo();
    }elseif ($msg[0] == delcard) {
        $ch = checkRoom($room,ROUND_START);
        if($ch !== true) return $ch;
        $player = $room->getPlayerByNameOrId($fromQQ);
        if(!$player) return "不在游戏中";
        $ids = $msg[1];
        $handcard = $room->delcardByRound($ids);
        setRoom($room,$fromGroup);
        return "handcard: " . formatcard($handcard);
    }
    elseif ($msg[0] == appcd) {
        $ch = checkRoom($room,ROUND_START);
        if($ch !== true) return $ch;
        // return $room->dmid;
        $player = $room->getPlayerByNameOrId($fromQQ);
        if(!$player) return "不在游戏中1";
        $id = $msg[1];
        $cards = $msg[2];
        $ch = checkRe([$id,$cards]);
        if(!$ch) return $ch;
        $player = $room->getPlayerByNameOrId($id);
        if(!$player) return "不在游戏中";
        
        $player->addcards($cards);
        $room->updatePlayerInfo($player);
        setRoom($room,$fromGroup);
        return "墓地: " . formatcard($player->qipai);
    }
    elseif ($msg[0] == opt) {
        $ch = checkRoom($room,ROUND_START);
        if($ch !== true) return $ch;
        $ch = $room->getPlayerByNameOrId($fromQQ);
        if(!$ch) return "不在游戏";

    
        $res = "";
        foreach ($msg as $key => $value) {
            if($key > 0&&!empty($value)){
                $re = $room->optsetvalue($value);
                if($re === false) return "输入不合法";
                $res .= $re . "\n";
            }
        }

        setRoom($room,$fromGroup);
        return $res;

    }
}

/*玩家回合开始  
    pos key
*/
function nextuserroundstart($fromGroup,$CQ){
    $pos = MyRedis::get("rounduser".$fromGroup);
    $rolldata = MyRedis::get("rolldata".$fromGroup);
    $usernum = count($rolldata); // roll点人数

    if ($pos == null) {
        $pos = 0;
    }else{
        $pos = ($pos + 1) % $usernum; 
    }
    MyRedis::set("rounduser".$fromGroup,$pos);
    $gameuser = MyRedis::get("gameuser".$fromGroup);
    // $name = $gameuser[$rolldata[$pos]]['card'];
    $CQ->sendGroupMsg($fromGroup, getusername($rolldata[$pos],$fromGroup) . " 你的回合"); 
}
/*玩家回合结束*/
function userroundend($fromQQ,$fromGroup,$CQ){
    $pos = MyRedis::get("rounduser".$fromGroup);
    $rolldata = MyRedis::get("rolldata".$fromGroup);
    if($rolldata[$pos] != $fromQQ) return "error 非你的回合";
    nextuserroundstart($fromGroup,$CQ);
}
/*检测权限*/
function checkauth($fromGroup,$fromQQ){
    $cardaddhost = MyRedis::get("cardaddhost".$fromGroup);  
    if(!empty($cardaddhost) && in_array($fromQQ, $cardaddhost)){
        return true;
    }else{
        return "权限不足 管理员才能开启";
    }
}

/*群组洗牌*/
function cardshuffle($fromGroup){
    $group = MyRedis::get("group".$fromGroup);
    if(empty($group)) return "群组无绑定";

    foreach ($group as $key => $value) {
        $cards = MyRedis::get("cardset".$value);
        $cards1 = MyRedis::get("cardset1".$value);


        $cards1 = $cards1? $cards1 : [];
        $cards = $cards? $cards:[];

        $cards = $cards + $cards1;
        $cards1 = [];

        MyRedis::set("cardset".$value,$cards);
        MyRedis::set("cardset1".$value,$cards1);
    }

    return true;
}
/*拼接@*/
function getusername($fromQQ,$fromGroup){
    // $gameuser = MyRedis::get("gameuser".$fromGroup);
    $gameuser = getuser();
    return isset($gameuser) ? "@".$gameuser['nickname'] ." \n" : "@$fromQQ \n";
}
function getCardbyId($id){
    $sql = "select * from card where id = $id";
    $card = getdb()->query($sql);
    if(empty($card)) return "查不到卡牌id";
    return $card[0]['id'] . "    " . $card[0]['c_name'] . "    " . $card[0]['effect'];
}
function getId(){
    $ids = MyRedis::get("cardsetids");
    if(!$ids){
        $ids = 1;
    }else{
        $ids++;
    }

    MyRedis::set("cardsetids",$ids);
    return $ids;
}

function msgformat($msg){
    if(empty($msg)) die();
    $info = explode(" ",$msg);//$msg
    $re = [];
    foreach ($info as $key => $value) {
        if(!empty($value)){
            $re[] = $value;
        }
    }

    if(!defined($re[0])) exit;
    return $re;
}

function getmycard($fromQQ,$format = true){
    $db = getdb();
    if($fromQQ == "dm"){
        $cards = $db->query("select * from card order by id");
    }else{
        $cards = $db->query("select * from card where fromqq = $fromQQ order by id");
    }
    
    if(empty($cards)) return "暂无卡牌";

    if(!$format){
        return $cards;
    }
    // foreach ($cards as $card) {
    //     $re .= $card['id'] . ":" . $card['c_name'] . ", ";
    // }
    return formatcard($cards);
}

function formatcard($cards){
    if(empty($cards)) return "";
    foreach ($cards as $card) {
        $re .= $card['id'] . ":" . $card['c_name'] . ", ";
    }
    return $re;
}

function checkdm(){
    $user = getuser();

    if($user != null && $user['isdm'] == 1) return true;
    return false;
}
function getUserInfoByQQOrName($from){

    $user = getdb()->query("select * from user where fromqq = '$from' or nickname = '$from'");
    if(empty($user)){
        return null;
    }
    return $user[0];
}

function userformat($user){
    return "hp : " . $user['lifevalue'] . "   mp : " .$user['bluequantity'] . "   xp : " .$user['xp'] . "   attr : ".$user['characteristic'];
}

function formatRoom($room){
    if(empty($room)){
        return "群内无游戏";
    }
    return $room->roomformatInfo();
}

function checkRe($data){
    if(empty($data) || !is_array($data)){
        return false;
    }
    foreach ($data as $key => $value) {
        if(empty($value)){
            return false;
        }
    }
    return true;

}
/*检测房间状态*/
function checkRoom($room,$status = GAME_START){
    if(empty($room)){
        return "游戏不存在";
    }
    else if ($room->status != $status) {
        return "游戏状态错误";
    }
    else{
        return true;
    }
}
// 提交
// ----------
// [接口返回][200 OK
// ]array(9) {
//   ["type"]=>
//   int(2)
//   ["subType"]=>
//   int(1)
//   ["msgID"]=>
//   int(1311)
//   ["time"]=>
//   int(1543915007)
//   ["loginQQ"]=>
//   int(2138353282)
//   ["qq"]=>
//   int(837424187)
//   ["group"]=>
//   int(99437797)
//   ["msg"]=>
//   string(11) "cardshuffle"
//   ["font"]=>
//   int(51153648)
// }
// <br />
// <b>Fatal error</b>:  Uncaught Error: Unsupported operand types in D:\zydev\CQAir_With_Dice2.2.6\CQAir_With_Dice2.2.6\app\php_sdk_2.0\CoolQ.demo.php:494
// Stack trace:
// #0 D:\zydev\CQAir_With_Dice2.2.6\CQAir_With_Dice2.2.6\app\php_sdk_2.0\CoolQ.demo.php(117): _eventmsgcard('cardshuffle', 837424187, 99437797, Object(CoolQ))
// #1 D:\zydev\CQAir_With_Dice2.2.6\CQAir_With_Dice2.2.6\app\php_sdk_2.0\CoolQ.event.php(43): _event_GroupMsg(Object(CoolQ), 1, 1543915007, 1311, 99437797, 837424187, 'cardshuffle', Array)
// #2 D:\zydev\CQAir_With_Dice2.2.6\CQAir_With_Dice2.2.6\app\php_sdk_2.0\CoolQ.event.php(113): treatEvent(Object(CoolQ), Array)
// #3 D:\zydev\CQAir_With_Dice2.2.6\CQAir_With_Dice2.2.6\app\php_sdk_2.0\index.php(12): include('D:\\zydev\\CQAir_...')
// #4 {main}
//   thrown in <b>D:\zydev\CQAir_With_Dice2.2.6\CQAir_With_Dice2.2.6\app\php_sdk_2.0\CoolQ.demo.php</b> on line <b>494</b><br />
// 。
// ResponseHeader：HTTP/1.1 200 OK
// Connection: Keep-Alive
// Date: Tue, 04 Dec 2018 09:16:47 GMT
// Keep-Alive: timeout=5, max=100
// Transfer-Encoding: chunked
// Content-Type: text/html; charset=UTF-8
// Server: Apache/2.4.23 (Win32) OpenSSL/1.0.2j mod_fcgid/2.3.9
// X-Powered-By: PHP/7.0.12

